package com.dys.controller;

import com.dys.pojo.User;
import com.dys.service.UserService;
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

/**
 * @className: com.dys.controller.ScopeController
 * @description: 作用域传值
 * @author: pine cone
 * @version: v1.0.0
 * @createTime: 2024/10/27 17:16
 */
@Controller
public class ScopeController {

    @Autowired
    private UserService userService;

    /*
     * request,session 这两个域直接放在参数列表上即可,SpringMVC就可以给我们注入
     * ServletContext对象(application域) 不能直接放在参数列表上的
     * */
    @RequestMapping(value = {"/setData"})
    public String setData(HttpServletRequest request, HttpSession session) {
        List<User> list = userService.findAllUsers();

        // 向3个作用域中存入数据
        request.setAttribute("requestMessage", "reqMessage");
        request.setAttribute("users", list);

        session.setAttribute("sessionMessage", "sessionMessage");
        session.setAttribute("users", list);

        ServletContext application = request.getServletContext();
        application.setAttribute("applicationMessage", "applicationMessage");
        application.setAttribute("users", list);

        // 跳转到显示数据界面
        return "forward:/showScopeDataPage.jsp";
    }

    /**
     * 主要是对请求域传递数据进行了API上的封装
     * 可以降低controller域servlet的耦合度，
     * 重定向下无法使用Model进行传递域中的数据
     * model中的字符串类型的键值对信息会转换为请求参数,转发给目标组件
     *
     * @param model 模型对象
     * @return 跳转的页面
     */
    @RequestMapping(value = {"/setDataByModel"}, method = RequestMethod.GET)
    public String setDataByModel(Model model) {
        List<User> list = userService.findAllUsers();
        model.addAttribute("modelMessage", "ModelMessage");
        model.addAttribute("users", list);
        return "forward:/showScopeDataPage.jsp";
        // return "redirect:/showScopeDataPage.jsp";
    }

    /**
     * Model 数据
     * View 视图
     * 重定向的数据会以param形式带过去
     *
     * @return
     */
    @RequestMapping("/setDataByModelAndView")
    public ModelAndView setDataByModelAndView() {
        ModelAndView mv = new ModelAndView();
        Map<String, Object> model = mv.getModel();
        model.put("modelAndViewMessage", "modelAndViewMessage");
        model.put("users", userService.findAllUsers());
        // mv.setViewName("forward:/showScopeDataPage.jsp");
        mv.setViewName("redirect:/showScopeDataPage.jsp");
        return mv;
    }
}
